package com.czk.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/28 10:59
 */
public class NettyClient {
    public void connect(String host, Integer port) {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new MyClientChannelInitializer());
            // 连接
            // 拿到自己的通道
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            // 添加监听器，处理重连
            channelFuture.addListener(new MyChannelFutureListener());
            channelFuture.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyClient client = new NettyClient();
        client.connect("localhost", 7379);
    }
}
